package com.handu.luna.boss.controller;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Base64;
import java.util.List;

import javax.validation.Valid;

import com.handu.luna.core.domain.promotion.CreditGoods;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.handu.luna.core.domain.goods.Goods;
import com.handu.luna.core.domain.promotion.CreditGoodsGoods;
import com.handu.luna.core.domain.searchVo.GoodsSearch;

@Controller
@RequestMapping("/promotion/creditgoodsgoods/*")
public class CreditGoodsGoodsController extends BaseController {

	@RequestMapping(value = { "index/{creditGoodsId}" })
	public BossModel index(@PathVariable long creditGoodsId, @PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable) {

        CreditGoods creditGoods = context.getCreditGoodsRepository().findOne(creditGoodsId);

		return createModel("promotion/creditgoodsgoods/index")
				.add("creditgoodsgoodsPage", context.getCreditGoodsGoodsRepository().findByCreditGoodsId(creditGoodsId, pageable))
                .add("viewState", "")
				.add("creditGoodsId", creditGoodsId)
                .add("creditGoods",creditGoods);
	}

	@RequestMapping(value = "add/{creditGoodsId}")
	public BossModel add(@PathVariable long creditGoodsId) {

        CreditGoods creditGoods = context.getCreditGoodsRepository().findOne(creditGoodsId);

		return createModel("promotion/creditgoodsgoods/add_info")
				.add("goodsSearch", new GoodsSearch())
				.add("creditGoodsId", creditGoodsId)
				.add("brands", context.getBrandRepository().findAll())
				.add("categorys", context.getCategoryRepository().findAll())
                .add("creditGoods",creditGoods);
	}

	@RequestMapping(value = "edit/{creditGoodsId}/{id}")
	public BossModel add(@PathVariable long creditGoodsId, @PathVariable long id) {

        CreditGoods creditGoods = context.getCreditGoodsRepository().findOne(creditGoodsId);

        return createModel("promotion/creditgoodsgoods/edit")
                .add("spg", context.getCreditGoodsGoodsRepository().findOne(id))
                .add("creditGoodsId", creditGoodsId)
                .add("creditGoods", creditGoods);
    }

	@RequestMapping(value = "list/{creditGoodsId}", method = RequestMethod.POST)
	public BossModel list(GoodsSearch goodsSearch, @PathVariable long creditGoodsId, @PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable) throws UnsupportedEncodingException {

        CreditGoods creditGoods = context.getCreditGoodsRepository().findOne(creditGoodsId);
		Page<Goods> goodsList = context.getGoodsRepository().findAll(Goods.topicSearchGoods(goodsSearch), pageable);
		for (Goods good : goodsList) {
			CreditGoodsGoods creditGoodsGoods = context.getCreditGoodsGoodsRepository().findByCreditGoodsIdAndGoodsId(creditGoodsId, good.getId());
            if (creditGoodsGoods != null) {
                good.setCreditGoodsGoods(creditGoodsGoods);
            }
		}
		return createModel("promotion/creditgoodsgoods/info")
				.add("goodsPage", goodsList)
				.add("goodsSearch", goodsSearch)
				.add("creditGoodsId", creditGoodsId)
				.add("brands", context.getBrandRepository().findAll())
				.add("categorys", context.getCategoryRepository().findAll())
                .add("creditGoods",creditGoods)
				.add("viewState", Base64.getEncoder().encodeToString(JSONObject.fromObject(goodsSearch).toString().getBytes("UTF-8")));
    }

    @RequestMapping(value = "list/{creditGoodsId}", method = RequestMethod.GET)
	public BossModel list(String viewState, @PathVariable long creditGoodsId, @PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable) throws UnsupportedEncodingException {
        CreditGoods creditGoods = context.getCreditGoodsRepository().findOne(creditGoodsId);
		GoodsSearch search;
		if (viewState != null && !viewState.trim().equals("")) {
			// 解析传递过来的查询json字符串
			search = (GoodsSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState), "UTF-8")), GoodsSearch.class);
        } else {
			search = new GoodsSearch();
		}
		Page<Goods> goodsList = context.getGoodsRepository().findAll(Goods.topicSearchGoods(search), pageable);
		for (Goods good : goodsList) {
			CreditGoodsGoods creditGoodsGoods = context.getCreditGoodsGoodsRepository().findByCreditGoodsIdAndGoodsId(creditGoodsId, good.getId());
            if (creditGoodsGoods != null) {
				 good.setCreditGoodsGoods(creditGoodsGoods);
			}
		}
		return createModel("promotion/creditgoodsgoods/info")
				.add("goodsPage", goodsList)
                .add("goodsSearch", search)
				.add("creditGoodsId", creditGoodsId)
				.add("brands", context.getBrandRepository().findAll())
                .add("creditGoods",creditGoods)
				.add("categorys", context.getCategoryRepository().findAll())
				.add("viewState", viewState == null ? "" : viewState);
	}

	@RequestMapping(value = "save/{creditGoodsId}", method = RequestMethod.POST)
	@InitBinder(value={"limitNumber","credit","money","creditType","isExchange"})
	public BossModel save(@Valid @ModelAttribute("spg") final CreditGoodsGoods spg, @PathVariable int creditGoodsId, final BindingResult bindingResult, RedirectAttributes redirectAttributes, @PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable) {

        CreditGoods creditGoods = context.getCreditGoodsRepository().findOne((long)creditGoodsId);
		if ("".equals(spg.getLimitNumber())) {
			bindingResult.rejectValue("limitNumber", "", "请输入数量");
		}
		if ("".equals(spg.getCredit())) {
			bindingResult.rejectValue("credit", "", "请输入积分");
		}
		/*if ("".equals(spg.getMoney())) {
			bindingResult.rejectValue("money", "", "请输入现金");
		}*/
		if (bindingResult.hasErrors()) {
			return createModel("promotion/creditgoodsgoods/edit")
                    .add("spg", context.getCreditGoodsGoodsRepository().findOne(spg.getId()))
                    .add("creditGoods",creditGoods)
                    .add("creditGoodsId", creditGoodsId);
        }
        String messagePrefix = spg.getSucessFlashMessage("");
		context.getCreditGoodsGoodsRepository().save(spg);
		return createModel("promotion/creditgoodsgoods/index")
				.add("creditgoodsgoodsPage", context.getCreditGoodsGoodsRepository().findByCreditGoodsId(creditGoodsId, pageable))
                .add("creditGoodsId", creditGoodsId)
                .add("creditGoods",creditGoods)
				.add("message", messagePrefix);
	}

	@RequestMapping(value = "ajaxsave", method = RequestMethod.POST)
	public BossModel save(long idd, int spidd, int creditd, BigDecimal moneyd, int isExchanged, int limitNumberd, String viewState,
                          @PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable) throws UnsupportedEncodingException {
		List<Goods> goodsCheckDelete = context.getGoodsRepository().findUnTrash(idd);
		if (!goodsCheckDelete.isEmpty()) {
			CreditGoodsGoods creditGoodsGoods = context.getCreditGoodsGoodsRepository().findByCreditGoodsIdAndGoodsId(spidd,idd);
            if(creditGoodsGoods == null) {
                creditGoodsGoods = new CreditGoodsGoods();
            }
			creditGoodsGoods.setCreditGoodsId(spidd);
			creditGoodsGoods.setGoodsId(idd);
			creditGoodsGoods.setCredit(creditd);
			creditGoodsGoods.setIsExchange(isExchanged);
			creditGoodsGoods.setMoney(moneyd);
			creditGoodsGoods.setLimitNumber(limitNumberd);
			context.getCreditGoodsGoodsRepository().save(creditGoodsGoods);
		}
		GoodsSearch search;
		if (StringUtils.isNotBlank(viewState)) {
			search = (GoodsSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState), "UTF-8")), GoodsSearch.class);
        } else {
			search = new GoodsSearch();
		}
		Page<Goods> goodsList = context.getGoodsRepository().findAll(Goods.topicSearchGoods(search), pageable);
		for (Goods good : goodsList) {
			CreditGoodsGoods creditGoodsGoods = context.getCreditGoodsGoodsRepository().findByCreditGoodsIdAndGoodsId(spidd, good.getId());
            if (creditGoodsGoods != null) {
				 good.setCreditGoodsGoods(creditGoodsGoods);
			}
		}

        CreditGoods creditGoods = context.getCreditGoodsRepository().findOne((long)spidd);
		return createModel("promotion/creditgoodsgoods/goods_table")
				.add("goodsPage", goodsList)
                .add("goodsSearch", search)
                .add("creditGoods",creditGoods)
				.add("creditGoodsId", spidd)
                .add("viewState", viewState);
	}

    @RequestMapping(value = "ajaxDelete", method = RequestMethod.POST)
	public BossModel delete(long goodsId,long creditGoodsId,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable,String viewState) throws UnsupportedEncodingException {

        CreditGoodsGoods creditGoodsGoods = context.getCreditGoodsGoodsRepository().findByCreditGoodsIdAndGoodsId(creditGoodsId,goodsId);

        context.getCreditGoodsGoodsRepository().delete(creditGoodsGoods);

		GoodsSearch search;
		if (StringUtils.isNotBlank(viewState)) {
			search = (GoodsSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState), "UTF-8")), GoodsSearch.class);
        } else {
			search = new GoodsSearch();
		}
		Page<Goods> goodsList = context.getGoodsRepository().findAll(Goods.topicSearchGoods(search), pageable);
		for (Goods good : goodsList) {
			CreditGoodsGoods creditGoodsGoods2 = context.getCreditGoodsGoodsRepository().findByCreditGoodsIdAndGoodsId(creditGoodsId, good.getId());
            if (creditGoodsGoods2 != null) {
				 good.setCreditGoodsGoods(creditGoodsGoods2);
			}
		}

        CreditGoods creditGoods = context.getCreditGoodsRepository().findOne(creditGoodsId);
		return createModel("promotion/creditgoodsgoods/goods_table")
				.add("goodsPage", goodsList)
                .add("goodsSearch", search)
                .add("creditGoods",creditGoods)
				.add("creditGoodsId", creditGoodsId)
                .add("viewState", viewState);
	}

	@RequestMapping(value = "delete", method = RequestMethod.POST)
	public BossModel delete(long id, int spid, @PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable) {
		context.getCreditGoodsGoodsRepository().delete(id);
        CreditGoods creditGoods = context.getCreditGoodsRepository().findOne((long)spid);
		return createModel("promotion/creditgoodsgoods/creditgoodsgoods_table")
				.add("creditgoodsgoodsPage", context.getCreditGoodsGoodsRepository().findByCreditGoodsId(spid, pageable))
                .add("creditGoods",creditGoods)
				.add("creditGoodsId", spid);
	}
}
